<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="queryParams" label-width="80px">
      <el-form-item label="房间名称">
        <el-input v-model="queryParams.roomName" clearable placeholder="请输入房间名称" />
      </el-form-item>
      <el-form-item label="房间状态">
        <el-select v-model="queryParams.roomStatus" clearable style="width: 120px">
          <el-option label="全部" value="" />
          <el-option label="直播中" value="1" />
          <el-option label="未开播" value="0" />
          <el-option label="已结束" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表：横向滚动，操作列锁定 -->
    <div class="table-wrapper">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        :scroll-x="1200"
      >
        <el-table-column type="index" width="60" label="序号" fixed="left" />
        <el-table-column label="头像" width="70" fixed="left">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="roomName" label="直播间名称" width="160" />
        <el-table-column prop="roomId" label="房间ID" width="90" />
        <el-table-column prop="creatorName" label="创建人" width="120" />
        <el-table-column prop="roomStatus" label="状态" width="90">
          <template #default="{ row }">
        {{ roomStatusMap[row.roomStatus] }}
      </template>
        </el-table-column>
        <el-table-column prop="viewerCount" label="观看人数" width="90" />
        <el-table-column prop="followCount" label="关注人数" width="90" />
        <el-table-column prop="coinCount" label="金币数" width="90" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <!-- 操作列：锁定 + 一行显示 -->
        <el-table-column
          label="操作"
          fixed="right"
          width="320"
          class-name="nowrap-operation"
        >
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="openViewer(row)">观看</el-button>
            <el-button size="small" type="warning" @click="openGift(row)">礼物</el-button>
            <el-button size="small" type="success" @click="openBarrage(row)">弹幕</el-button>
            <el-button size="small" @click="closeRoom(row)">关闭</el-button>
            <el-button size="small" type="danger" @click="deleteRoom(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <!-- 观看记录弹窗（带头像+分页） -->
    <el-dialog v-model="viewerVisible" title="观看记录" width="700px">
      <el-table :data="viewerData">
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column label="头像" width="60">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="观看人" />
        <el-table-column prop="viewerId" label="用户ID" width="80" />
        <el-table-column prop="enterTime" label="进入时间" width="150" />
        <el-table-column prop="leaveTime" label="离开时间" width="150" />
        <el-table-column prop="watchDuration" label="观看时长(秒)" width="100" />
      </el-table>
      <pagination
        :total="viewerTotal"
        v-model:page="viewerQuery.pageNum"
        v-model:limit="viewerQuery.pageSize"
      />
    </el-dialog>

    <!-- 礼物记录弹窗（带头像+分页） -->
    <el-dialog v-model="giftVisible" title="礼物记录" width="700px">
      <el-table :data="giftData">
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column label="头像" width="60">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="送礼人" />
        <el-table-column prop="senderId" label="用户ID" width="80" />
        <el-table-column prop="giftName" label="礼物" />
        <el-table-column prop="createTime" label="时间" width="150" />
      </el-table>
      <pagination
        :total="giftTotal"
        v-model:page="giftQuery.pageNum"
        v-model:limit="giftQuery.pageSize"
      />
    </el-dialog>

    <!-- 弹幕记录弹窗（带头像+分页） -->
    <el-dialog v-model="barrageVisible" title="弹幕记录" width="700px">
      <el-table :data="barrageData">
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column label="头像" width="60">
          <template #default="{ row }">
            <el-avatar :src="row.senderAvatar" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="发送人" />
        <el-table-column prop="senderId" label="用户ID" width="80" />
        <el-table-column prop="content" label="弹幕内容" />
        <el-table-column prop="createTime" label="时间" width="150" />
      </el-table>
      <pagination
        :total="barrageTotal"
        v-model:page="barrageQuery.pageNum"
        v-model:limit="barrageQuery.pageSize"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { reqRoomsPage,reqRoomsWatchesPage,reqRoomsGiftsPage,reqRoomsBarragePage } from '@/api/rooms/index'
import { LiveRoom,LiveRoomResponse,LiveRoomWatchesResponse,LiveRoomBarrageResponse,LiveRoomGiftResponse,WatchHistory,GiftHistory,BarrageRecording} from '@/api/rooms/type'
import { R, page, PageQuery, emptyPageInfo, ResponseData,PageInfo } from "@/api/common/type";

 const roomStatusMap: Record<string, string> = {
  '0': '未开播',
  '1': '直播中',
  '2': '已结束'
};

/* ========== 搜索 + 房间列表 ========== */
const queryParams = reactive({
  roomName: '',
  roomStatus: '',
  dateRange: [],
  pageNum: 1,
  pageSize: 10
})
const loading = ref(false)
const total = ref(0)
const tableData = ref<LiveRoom[]>([])

/* ========== 弹窗分页 ========== */
const viewerVisible = ref(false)
const giftVisible   = ref(false)
const barrageVisible= ref(false)

const viewerQuery = reactive({ pageNum: 1, pageSize: 10 })
const giftQuery   = reactive({ pageNum: 1, pageSize: 10 })
const barrageQuery= reactive({ pageNum: 1, pageSize: 10 })

const viewerData  = ref<any[]>([])
const giftData    = ref<any[]>([])
const barrageData = ref<any[]>([])
const viewerTotal = ref(0)
const giftTotal   = ref(0)
const barrageTotal= ref(0)

const handleQuery = async() => {
  loading.value = true

  const pageInfo: PageInfo = {
    pageSize: queryParams.pageSize,
    pageIndex: queryParams.pageNum,
  }
  const room: LiveRoom = { ...queryParams }
  if (queryParams.dateRange.length > 1) {
    room.beginTime = queryParams.dateRange[0] + 'T00:00:00'
    room.endTime = queryParams.dateRange[1] + 'T23:59:59'
  }
  const query: PageQuery<LiveRoom> = {
    filterData: room,
    pageInfo: pageInfo,
  }

  const result: LiveRoomResponse = await reqRoomsPage(query)

  if (result && result.code === 200) {
    tableData.value = result.data.records
    total.value = result.data.total
  } else {
    return Promise.reject(new Error(result.message))
  }
  loading.value = false
}
function resetQuery () {
  Object.assign(queryParams, { roomName: '', status: '', dateRange: [], pageNum: 1 })
  handleQuery()
}


const openViewer = async(row: LiveRoom) => {
  viewerVisible.value = true;

  const pageInfo: PageInfo = {
    pageSize: viewerQuery.pageSize,
    pageIndex: viewerQuery.pageNum,
  }
  // const watches: WatchHistory = { ...queryParams }

  const query: PageQuery<WatchHistory> = {
    filterData: {roomId: row.roomId},
    pageInfo: pageInfo
  }

  const result: LiveRoomWatchesResponse = await reqRoomsWatchesPage(query)

  if (result && result.code === 200) {

    viewerTotal.value = result.data.total
    viewerData.value = result.data.records
  } else {
    return Promise.reject(new Error(result.message))
  }


}
const openGift = async(row: LiveRoom) => {
  giftVisible.value = true;

  const pageInfo: PageInfo = {
    pageSize: giftQuery.pageSize,
    pageIndex: giftQuery.pageNum,
  }

  const query: PageQuery<GiftHistory> = {
    filterData: {roomId: row.roomId},
    pageInfo: pageInfo
  }
  const result: LiveRoomGiftResponse = await reqRoomsGiftsPage(query)

  if (result && result.code === 200) {

    giftTotal.value = result.data.total
    giftData.value = result.data.records
  } else {
    return Promise.reject(new Error(result.message))
  }


}

const openBarrage = async(row: LiveRoom) => {
  barrageVisible.value = true;

  const pageInfo: PageInfo = {
    pageSize: barrageQuery.pageSize,
    pageIndex: barrageQuery.pageNum,
  }
  // const watches: WatchHistory = { ...queryParams }

  const query: PageQuery<BarrageRecording> = {
    filterData: {roomId: row.roomId},
    pageInfo: pageInfo
  }
  const result: LiveRoomBarrageResponse = await reqRoomsBarragePage(query)

  if (result && result.code === 200) {

    barrageTotal.value = result.data.total
    barrageData.value = result.data.records
  } else {
    return Promise.reject(new Error(result.message))
  }

}


function closeRoom(row: LiveRoom) {
  ElMessage.success(`已关闭房间 ${row.roomId}`)
}

function deleteRoom(row: LiveRoom) {

  ElMessage.success(`已删除房间 ${row.roomId}`)
}

onMounted(handleQuery)
</script>

<style scoped>
.app-container {
  padding: 20px;
}
/* 表格容器可横向滚动，操作列不折行 */
.table-wrapper {
  overflow-x: auto;
}
.nowrap-operation {
  white-space: nowrap;
}
</style>